/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.system;

import java.awt.KeyboardFocusManager;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import main.ServicesList;
import model.system.SystemGroup;
import model.system.SystemUser;
import org.apache.log4j.Logger;
import utility.NameValueList;
import utility.com.Md5;
import view.DialogTemplate;


/**
 *
 * @author Yusup Jauhari Shandi <in.visi>
 */
public class UserFrm extends DialogTemplate{

     private SystemUser user;
     private DefaultComboBoxModel listGroup;
     private static Logger log = Logger.getLogger(UserFrm.class);
     private Object oldValue, newValue;
     
    public UserFrm() {
        
         super(ServicesList.MAIN_FRAME, true);
        initComponents();
    }

    /**
     * Creates new form UserFrm
     */
    
    public UserFrm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnSave = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        txtFullName = new javax.swing.JTextField();
        txtPhone = new javax.swing.JTextField();
        txtPasswd = new javax.swing.JPasswordField();
        cmbGroup = new javax.swing.JComboBox();
        chkAktif = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        jLabel1.setText("Nama User :");

        jLabel2.setText("Nama Lengkap :");

        jLabel3.setText("Kelompok :");

        jLabel4.setText("Telepon :");

        jLabel5.setText("Password :");

        txtUserName.setText("jTextField1");

        txtFullName.setText("jTextField2");

        txtPhone.setText("jTextField4");

        txtPasswd.setText("jPasswordField1");

        cmbGroup.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        chkAktif.setText("Non Aktif");
        chkAktif.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkAktifActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(chkAktif)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(btnSave)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btnCancel))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtPasswd)
                            .addComponent(txtFullName)
                            .addComponent(txtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmbGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtFullName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cmbGroup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtPasswd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(chkAktif)
                        .addGap(0, 25, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnSave)
                            .addComponent(btnCancel))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        validasi();
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void chkAktifActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkAktifActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_chkAktifActionPerformed

   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSave;
    private javax.swing.JCheckBox chkAktif;
    private javax.swing.JComboBox cmbGroup;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField txtFullName;
    private javax.swing.JPasswordField txtPasswd;
    private javax.swing.JTextField txtPhone;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables

    @Override
    public int execute(int id) {
        setLocationRelativeTo(null);
        initForm();
        if (id!=0) { loadData(id); }
        setTitle((id!=0?"Edit ":"Tambah ")+"Pengguna");
        setVisible(true);
        if (user!=null) {
        return user.getUserId();}
        else { return 0; }
    }

    @Override
    public void initForm() {
        user = new SystemUser();
        listGroup = new DefaultComboBoxModel();
        listGroup = ServicesList.getSystemGroupService().getCombo(null, null,false);
        txtUserName.setText("");
        txtFullName.setText("");
        txtPhone.setText("");
        txtPasswd.setText("");
        chkAktif.setSelected(false);
        cmbGroup.setModel(listGroup);
    }

    @Override
    public void loadData(int id) {
        user = ServicesList.getSystemUserService().getSystemUser(id);
        if (user != null) {
            txtUserName.setText(user.getUserName());
            txtFullName.setText(user.getFullName());
            txtPhone.setText(user.getPhone());
            chkAktif.setSelected(user.getSuspended());
            
           //cmbGroup.setSelectedIndex(NameValueList.indexOf(listGroup, String.valueOf(user.getSystemGroup().getGroupId())));
           // cmbGroup.setSelectedIndex(ServicesList.getSystemGroupService().getSelectedIndex(listGroup, String.valueOf(user.getSystemGroup().getGroupId())));
        }
    }

    @Override
    public void saveData() {
        user.setUserName(txtUserName.getText());
        user.setFullName(txtFullName.getText());
        user.setPhone(txtPhone.getText());
        user.setPasswd(Md5.setMd5(String.valueOf(txtPasswd.getPassword())));
        user.setSystemGroup(ServicesList.getSystemGroupService().getSystemGroup(Integer.parseInt(((NameValueList)cmbGroup.getSelectedItem()).getKey())));
        user.setSuspended(Boolean.valueOf(chkAktif.isSelected()));
        boolean saved = false;
        try{
            saved = ServicesList.getSystemUserService().save(user);
            
        } catch(Exception ex){
            log.error(ex);
            JOptionPane.showMessageDialog(this, "Data gagal disimpan."
            ,"Error",JOptionPane.ERROR_MESSAGE);
        }
        
        initButtonState(!saved);
    }

    @Override
    public void validasi() {
        boolean valid;
        
        valid = txtUserName.getText().equals("") ? false:true;
        if (!valid) {
            JOptionPane.showMessageDialog(this, "Nama User belum diisi.!"
            ,"Warinig",JOptionPane.WARNING_MESSAGE);}
        
        if (valid) { saveData(); }
    }

    @Override
    public void moveNext() {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.focusNextComponent();
    }

    @Override
    public void initButtonState(boolean status) {
        btnSave.setEnabled(status);
    }
}
